﻿package com.rbac.system.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.rbac.system.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.regex.Pattern;

/**
 * 短信服务实现类
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    
    @Value("${aliyun.sms.access-key-id}")
    private String accessKeyId;
    
    @Value("${aliyun.sms.access-key-secret}")
    private String accessKeySecret;
    
    @Value("${aliyun.sms.sign-name}")
    private String signName;
    
    @Value("${aliyun.sms.template.register}")
    private String registerTemplate;
    
    @Value("${aliyun.sms.template.login}")
    private String loginTemplate;
    
    @Value("${aliyun.sms.endpoint:dysmsapi.aliyuncs.com}")
    private String endpoint;
    
    private static final String PHONE_PATTERN = "^1[3-9]\\d{9}$";
    private static final Pattern pattern = Pattern.compile(PHONE_PATTERN);
    
    @Override
    public boolean sendVerificationCode(String phone, String code, String type) {
        try {
            String templateCode = getTemplateByType(type);
            if (templateCode == null) {
                log.error("未找到对应的短信模板: type={}", type);
                return false;
            }
            
            Client client = createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            
            if ("OK".equals(response.getBody().getCode())) {
                log.info("短信验证码发送成功: phone={}, type={}", phone, type);
                return true;
            } else {
                log.error("短信验证码发送失败: phone={}, type={}, code={}, message={}", 
                         phone, type, response.getBody().getCode(), response.getBody().getMessage());
                return false;
            }
        } catch (Exception e) {
            log.error("发送短信验证码异常: phone={}, type={}, error={}", phone, type, e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean sendSimpleSms(String phone, String content) {
        try {
            // 这里可以根据需要实现发送普通短信的逻辑
            // 通常需要预先在阿里云配置相应的短信模板
            log.info("发送普通短信: phone={}, content={}", phone, content);
            return true;
        } catch (Exception e) {
            log.error("发送普通短信失败: phone={}, content={}, error={}", phone, content, e.getMessage());
            return false;
        }
    }
    
    @Override
    public String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
    
    @Override
    public boolean isValidPhone(String phone) {
        return phone != null && pattern.matcher(phone).matches();
    }
    
    /**
     * 创建阿里云短信客户端
     */
    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setEndpoint(endpoint);
        return new Client(config);
    }
    
    /**
     * 根据类型获取短信模板
     */
    private String getTemplateByType(String type) {
        switch (type) {
            case "register":
                return registerTemplate;
            case "login":
                return loginTemplate;
            default:
                return null;
        }
    }
}


